package com.baturu.vin.honda.cleanData;

import java.io.*;

public class FileUtil {


    public static void readFile(String path, String charset, ReadLineListener listener) {
        readFile(path, charset, -1, listener);
    }

    public static void readFile(String path, String charset, int line, ReadLineListener listener) {
        FileInputStream fis = null;
        BufferedReader br = null;
        try {
            fis = new FileInputStream(path);
            br = new BufferedReader(new InputStreamReader(fis, charset));
            String s;
            int readLine = 0;
            while ((s = br.readLine()) != null) {
                if (listener != null) {
                    listener.onReadLine(s, br);
                }
                if (line < 0) {
                    continue;
                }
                readLine++;
                if (readLine >= line) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void readAndWriteFile(String in, String out, String inCharset, String outCharset, ReadAndWriteListener listener) {
        try {
            FileInputStream fis = new FileInputStream(in);
            FileOutputStream fos = new FileOutputStream(out);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis, inCharset));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, outCharset));
            ReadAndWriteFile0(br, bw, listener);
            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readAndWriteFile(String in, String out, String charset, ReadAndWriteListener listener) {
        readAndWriteFile(in, out, charset, charset, listener);
    }

    private static void ReadAndWriteFile0(BufferedReader br, BufferedWriter bw, ReadAndWriteListener listener) {
        String s;
        try {
            while ((s = br.readLine()) != null) {
                boolean b = listener.onReadLine(s, bw);
                if (b) {
                    bw.newLine();
                }
            }
            br.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    interface ReadLineListener {
        void onReadLine(String s, Reader reader) throws IOException;
    }


    interface ReadAndWriteListener {
        boolean onReadLine(String s, Writer writer) throws IOException;
    }


}
